#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<iostream>
#include<unistd.h>
#include <mutex>
using namespace std;
// 创建四个进程模拟抢票：
int ticket = 1000;
std::mutex m;
void *route(void *arg)
{
    char *id = (char *)arg;
    while (1)
    {   //保护临界区
        m.lock();
        if (ticket > 0) // 1. 判断
        {
            usleep(1000);                               // 模拟抢票花的时间
            printf("%s sells ticket:%d\n", id, ticket); // 2. 抢到了票
            ticket--;                                   // 3. 票数--
            m.unlock();

        }
        else
        {
            m.unlock();
            //这里还需要解锁否则到最后抢完票线程加锁后有其他线程不能被join进而阻塞住

            break;
        }
    }
    return nullptr;
}
int main()
{
    pthread_t t1, t2, t3, t4;

    pthread_create(&t1, NULL, route, (void *)"thread 1");
    pthread_create(&t2, NULL, route, (void *)"thread 2");
    pthread_create(&t3, NULL, route, (void *)"thread 3");
    pthread_create(&t4, NULL, route, (void *)"thread 4");

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);
}